//
//  InviteFriendViewController.swift
//  SmartHousekeeper
//
//  Created by 张磊 on 2020/2/22.
//  Copyright © 2020 LS. All rights reserved.
//

import UIKit
import Contacts
//邀请客人进入小区预约登记

class InviteFriendViewController: ContributionBaseViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    lazy var myContactStore: CNContactStore = {
        let cn:CNContactStore = CNContactStore()
        return cn
    }()
    let inviteFriendView = InviteFriendView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        
    }
    override func rightBtnAction(){
        print("更多")
    }
    func setUI() {
        self.baseView.company.isHidden = true
        self.baseView.addSubview(inviteFriendView)
        inviteFriendView.snp.makeConstraints { (make) in
            make.top.equalTo(self.baseView.rightBtn.snp.bottom);
            make.left.equalToSuperview();
            make.right.equalToSuperview();
            make.bottom.equalTo(self.baseView);
        }
        inviteFriendView.takeBookBlcok = {
                  
            print("调用通讯录")
            
            self.checkContactStoreAuth()
               
        }
        inviteFriendView.appointmentBlock = {
            let vc = InviteFriendSuceessViewController()
            self.navigationController?.pushViewController(vc, animated: true)
            print("立刻预约")
        }
        inviteFriendView.takePhotoBlcok = {
            print("选择图片")
            self.showBottomAlert()
        }
    }
    func checkContactStoreAuth(){
        switch CNContactStore.authorizationStatus(for: .contacts) {
        case .notDetermined:
            print("未授权")
            requestContactStoreAuthorization(myContactStore)
        case .authorized:
            print("已授权")
            readContactsFromContactStore(myContactStore)
        case .denied, .restricted:
            print("无权限")
        //可以选择弹窗到系统设置中去开启
        default: break
        }
    }
    func requestContactStoreAuthorization(_ contactStore:CNContactStore) {
        contactStore.requestAccess(for: .contacts, completionHandler: {[weak self] (granted, error) in
            if granted {
                print("已授权")
                self?.readContactsFromContactStore(contactStore)
            }
        })
    }
    func readContactsFromContactStore(_ contactStore:CNContactStore) {
        guard CNContactStore.authorizationStatus(for: .contacts) == .authorized else {
            return
        }
        
        let keys = [CNContactFamilyNameKey,CNContactGivenNameKey,CNContactPhoneNumbersKey]
        
        let fetch = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
        do {
            try contactStore.enumerateContacts(with: fetch, usingBlock: { (contact, stop) in
                //姓名
                let name = "\(contact.familyName)\(contact.givenName)"
                print(name)
                //电话
//                for labeledValue in contact.phoneNumbers {
//                    let phoneNumber = (labeledValue.value as CNPhoneNumber).stringValue
//                    print(phoneNumber)
//                }
                self.inviteFriendView.nameText.text = name
            })
        } catch let error as NSError {
            print(error)
        }
    }
    func showBottomAlert(){
        
        let alertController=UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

        let cancel=UIAlertAction(title:"取消", style: .cancel, handler: nil)
        let takingPictures=UIAlertAction(title:"拍照", style: .default)
        {
            action in
            self.goCamera()
            
        }
        let localPhoto=UIAlertAction(title:"本地图片", style: .default)
        {
            action in
            self.goImage()
            
        }
        alertController.addAction(cancel)
        alertController.addAction(takingPictures)
        alertController.addAction(localPhoto)
        self.present(alertController, animated:true, completion:nil)
        
    }
    // 去拍照
    func goCamera(){
                    
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            let  cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
            cameraPicker.allowsEditing = true
            cameraPicker.sourceType = .camera
            //在需要的地方present出来
            self.present(cameraPicker, animated: true, completion: nil)
        } else {
            
            print("不支持拍照")
            
        }

    }
    /// 去相册
    func goImage(){

        
        let photoPicker =  UIImagePickerController()
        photoPicker.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
        photoPicker.allowsEditing = true
        photoPicker.sourceType = .photoLibrary
        //在需要的地方present出来
        self.present(photoPicker, animated: true, completion: nil)
        
    }
    //代理
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {


        print("获得照片============= \(info)")
        
        let image : UIImage = info[UIImagePickerController.InfoKey.editedImage] as! UIImage

        //显示设置的照片
        self.inviteFriendView.carNoBtn.setImage(UIImage(named: ""), for: .normal)

        self.inviteFriendView.carNoBtn.setBackgroundImage(image, for: .normal)


        self.dismiss(animated: true, completion: nil)
    }
    
}
